package com.br.android.widingwheels.db;

import com.br.android.widingwheels.entidades.Gasto;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class WidingWheelsDAO extends WidingWheelsDataBase {

	public WidingWheelsDAO(Context context) {
		super(context);
	}
	
	public WidingWheelsCursor getAll(){
		String sql = WidingWheelsCursor.QUERY;
		SQLiteDatabase dataBase = getReadableDatabase();
		WidingWheelsCursor c = (WidingWheelsCursor) dataBase.rawQueryWithFactory(new WidingWheelsCursor.Factory(), sql, null, null);
		c.moveToFirst();
		return c;
	}
	
	public WidingWheelsCursor getTotalValores(){
		String sql = WidingWheelsCursor.QUERY_SOMA_VALORES;
		SQLiteDatabase dataBase = getReadableDatabase();
		WidingWheelsCursor c = (WidingWheelsCursor) dataBase.rawQueryWithFactory(new WidingWheelsCursor.Factory(), sql, null, null);
		c.moveToFirst();
		return c;
	}
	
	public WidingWheelsCursor getTotalValoresPorCategoria(){
		String sql = WidingWheelsCursor.QUERY_SOMA_VALORES_POR_CATEGORIA;
		SQLiteDatabase dataBase = getReadableDatabase();
		WidingWheelsCursor c = (WidingWheelsCursor) dataBase.rawQueryWithFactory(new WidingWheelsCursor.Factory(), sql, null, null);
		c.moveToFirst();
		return c;
	}

	public void inserirGasto(Gasto gasto, boolean compartilharLocalizacao){
		String sql = "";
		Object[] obj = null;
		if(compartilharLocalizacao){
			sql = "INSERT INTO gasto(nomegasto, datagasto, valorgasto, categoriagasto, latitude, longitude, nomelocal) VALUES(?, ?, ?, ?, ?, ?, ?)";
			obj = new Object[] {gasto.getNomeGasto(), gasto.getDataGasto(), gasto.getValorGasto(), gasto.getCategoriaGasto(), gasto.getLatitudeGasto(), gasto.getLongitudeGasto(), gasto.getNomeLocal()};
		} else {
			sql = "INSERT INTO gasto(nomegasto, datagasto, valorgasto, categoriagasto) VALUES(?, ?, ?, ?)";
			obj = new Object[] {gasto.getNomeGasto(), gasto.getDataGasto(), gasto.getValorGasto(), gasto.getCategoriaGasto()};
		}
		try {
			getWritableDatabase().execSQL(sql, obj);
		} catch (Exception e){
			Log.e("ERRO AO INSERIR GASTO", e.getMessage());
		}
	}
	
	public void excluirGasto(int id){
		String sql = "DELETE FROM gasto WHERE idgasto = ?";
		Object[] obj = new Object[]{id};
		try {
			getWritableDatabase().execSQL(sql, obj);
		} catch (Exception e) {
			Log.e("Erro ao excluir um gasto", e.toString());
		}
	}

	public void alterarGasto(Gasto gasto){
		String sql = "UPDATE gasto SET nomegasto = ?, valorgasto = ?, categoriagasto = ?, datagasto = ? WHERE idgasto = ?";
		Object[] obj = new Object[]{gasto.getNomeGasto(), gasto.getValorGasto(),
									gasto.getCategoriaGasto(), gasto.getDataGasto(), gasto.getIdGasto()};
		try {
			getWritableDatabase().execSQL(sql, obj);
		} catch (Exception e) {
			Log.e("Erro ao alterar um gasto", e.toString());
		}
	}
	
	
}
